package com.xbh.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: common-utils
 * @description: JWT处理Token
 * @author: 许宝华
 * @create: 2021-09-03 10:11
 */

public class JwtUtils {
    private static final Logger log = LoggerFactory.getLogger(JwtUtils.class);

    public JwtUtils() {
    }

    public static JSONObject getJwtPayload() throws ParseException {
        try {
            String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization");
            token = token.replace("Bearer ", "");
            JWSObject jwsObject = JWSObject.parse(token);
            JSONObject jsonObject = JSONUtil.parseObj(jwsObject.getPayload().toString());
            return jsonObject;
        } catch (Throwable var3) {
            throw var3;
        }
    }

    public static Long getUserId() throws ParseException {
        Long id = getJwtPayload().getLong("userId");
        return id;
    }

    public static String getUsername() throws ParseException {
        String username = getJwtPayload().getStr("username");
        return username;
    }

    public static Long getUserTentantId() throws IOException {
        try {
            Long tenantId = null;
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            String tenantIdStr = request.getParameter("Content-Tenant-Id");
            if (StrUtil.isNotBlank(tenantIdStr)) {
                tenantIdStr = new String((new BASE64Decoder()).decodeBuffer(tenantIdStr), "UTF-8");
                tenantId = Long.valueOf(tenantIdStr);
            }

            String basic = request.getHeader("Content-Tenant-Id");
            if (StrUtil.isNotBlank(basic)) {
                tenantIdStr = new String((new BASE64Decoder()).decodeBuffer(basic), "UTF-8");
                tenantId = Long.valueOf(tenantIdStr);
            }

            return tenantId;
        } catch (Throwable var4) {
            throw var4;
        }
    }

    public static String getAuthClientId() throws IOException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            String clientId = request.getParameter("client_id");
            if (StrUtil.isNotBlank(clientId)) {
                return clientId;
            } else {
                String basic = request.getHeader("Authorization");
                if (StrUtil.isNotBlank(basic) && basic.startsWith("Basic ")) {
                    basic = basic.replace("Basic ", "");
                    String basicPlainText = new String((new BASE64Decoder()).decodeBuffer(basic), "UTF-8");
                    clientId = basicPlainText.split(":")[0];
                }

                return clientId;
            }
        } catch (Throwable var4) {
            throw var4;
        }
    }

    public static List<String> getRoles() throws ParseException {
        JSONObject payload = getJwtPayload();
        if (payload != null && payload.size() > 0) {
            List<String> list = (List)payload.get("authorities", List.class);
            List<String> roles = (List)list.stream().collect(Collectors.toList());
            return roles;
        } else {
            return null;
        }
    }
}
